package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.web.AjaxResult;
import com.github.pagehelper.PageHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class StatementItemServiceImpl implements IStatementItemService {

    @Autowired
    private StatementItemMapper statementItemMapper;
    @Autowired
    private StatementMapper statementMapper;


    @Override
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<StatementItem>(statementItemMapper.selectForList(qo));
    }


    @Override
    public void save(StatementItem statementItem) {
        statementItemMapper.insert(statementItem);
    }

    @Override
    public StatementItem get(Long id) {
        return statementItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(StatementItem statementItem) {
        statementItemMapper.updateByPrimaryKey(statementItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            statementItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<StatementItem> list() {
        return statementItemMapper.selectAll();
    }

    @Override
    public List<StatementItem> queryByStatementId(Long statementId) {
        return statementItemMapper.queryByStatementId(statementId);
    }

    @Override
    @Transactional
    public void saveItems(List<StatementItem> items) {
        //集合中的最后一个元素只是为了保存价格，因此把最后一个元素删除只获取到其优惠价格即可
        StatementItem tempItem = items.remove(items.size() - 1);
        //获取优惠价格
        BigDecimal disCountPrice = tempItem.getItemPrice();
        System.out.println(disCountPrice);
        //通过结算单id获取结算单对象
        Statement statement = statementMapper.selectByPrimaryKey(tempItem.getStatementId());
        if(!Statement.STATUS_CONSUME.equals(statement.getStatus())){
            throw new BusinessException("只有是消费中的结算单才可进行结算单明细的保存");
        }
        //在进行保存操作时，需要先将原来已经存在的结算单明细数据删除都删除，在插入更新后的数据
        statementItemMapper.deleteItemByStatmentId(statement.getId());
        //定义总金额和总数量的变量
        BigDecimal totalAmount = new BigDecimal(0);
        BigDecimal totalQuantity = new BigDecimal(0);
        //循环过程中把结算单明细插入表中
        if(items.size() > 0){
            for (StatementItem item : items) {
                statementItemMapper.insert(item);
                totalAmount = totalAmount.add(item.getItemPrice().multiply(item.getItemQuantity()));
                totalQuantity = totalQuantity.add(item.getItemQuantity());
            }
        }
        //判断折扣金额是否大于总金额
        if(disCountPrice.compareTo(totalAmount) > 0){
            throw new BusinessException("优惠金额不能小于总金额");
        }
        //通过结算单id更新结算单相关数据
        statementMapper.updateStatementDecimal(statement.getId(),totalAmount,totalQuantity,disCountPrice);
    }

    @Override
    public void exportOP(Long statementId, HttpServletResponse response) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("结算单明细列表");
        Row row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("服务项名称");
        row1.createCell(1).setCellValue("服务项价格");
        row1.createCell(2).setCellValue("购买数量");
        List<StatementItem> items = statementItemMapper.queryItemByStatementId(statementId);
        for (int i = 0; i < items.size(); i++) {
            StatementItem statementItem = items.get(i);
            Row row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(statementItem.getItemName());
            row.createCell(1).setCellValue(String.valueOf(statementItem.getItemPrice()));
            row.createCell(2).setCellValue(String.valueOf(statementItem.getItemQuantity()));
        }
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        out.close();
        workbook.close();
    }
}
